/*
 * Copyright 2018 the original author or authors.
 * 
 * you can use the file or import project.but Do not take legal responsibility.
 * Only for learning communication.
 *
 * Java compiled version 1.8 or higher
 * 
 * 
 * 
 * 
 */
 
package org.demo.util;

import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.Map;
import java.util.Map.Entry;

import org.demo.util.bean.HttpResultBean;

/**
 * 封装http链接工具<br/>
 * 	与<code>ExaHttpClient</code>类部分功能重叠{@link ExaHttpClient}，区别
 * <ul>
 * 	<li>ExaHttpUtil类使用java基础类封装</li>
 * 	<li>ExaHttpClient依赖于apache的httpclient疯转</li>
 * </ul>
 * @author jx-air
 * @date 2018年2月24日 上午9:40:08
 * @version 1.0
 */
public class ExaHttpUtil {
	public static final String CHARSET_DEFAULT = "UTF-8";//默认编码方式
	private static int readTimeout = 5000;//设置读取超时时间，毫秒
	private static int connectTimeout = 5000;//设置链接超时时间，毫秒
	
	public static HttpResultBean get(String url) {
		return get(url,null,CHARSET_DEFAULT);
	}
	
	/**
	 * 封装http get请求
	 * @param url 请求地址
	 * @param paraMap 请求参数，无参数可为null
	 * @param charset 编码，参数为空或者null，使用默认编码 UTF-8
	 * @return 请求对象
	 */
	public static HttpResultBean get(String url,Map<String,String> paraMap,String charset) {
		long startTime = System.currentTimeMillis();//统计用时
		HttpResultBean result = new HttpResultBean();//封装返回结果
		
		InputStream inputStream = null;
		try {
			
			//拼接get请求参数
			if(paraMap !=null && paraMap.size() > 0) {
				StringBuffer tempUrl = new StringBuffer();
				for (Entry<String,String> entry : paraMap.entrySet()) {
					tempUrl.append(entry.getKey()).append("=").append(entry.getValue()).append("&");
				}
				url = url +"?" + tempUrl.substring(0,tempUrl.length()-1);
			}
			
			URL u = new URL(url);
			HttpURLConnection httpConn = (HttpURLConnection)u.openConnection();
			httpConn.setRequestMethod("GET");
			httpConn.setDoOutput(true);
			httpConn.setDoInput(true);
			httpConn.setReadTimeout(readTimeout);
			httpConn.setConnectTimeout(connectTimeout);
			
			int state = httpConn.getResponseCode();
			if(state == HttpURLConnection.HTTP_OK) {
				if(charset == null || "".equals(charset.trim())) {
					charset = CHARSET_DEFAULT;
				}
				
				inputStream = httpConn.getInputStream();
				StringBuffer sb = new StringBuffer();//返回结果
				int n = -1;
				byte[] bs = new byte[512];
				while((n=inputStream.read(bs))!=-1) {
					String temp = new String(bs,0,n,charset);
					sb.append(temp);
				}
				inputStream.close();
			}else {
				System.err.println("http get请求接口调用,错误,错误代码:" + state);
			}
			
			System.out.println("http get请求接口调用,返回结果:"+result.isStatus()+",返回报文:" + result.getResponse());
			System.out.println("http get请求接口调用,用时:" + ExaTimeUtil.useTime(startTime) + "秒");
		} catch (Exception e) {
			String useTime = ExaTimeUtil.useTime(startTime);
			System.err.println("http get请求接口调用,异常,用时:" + useTime + "秒");
			System.err.println("http get请求接口调用,异常信息:" +e.getMessage());
			e.printStackTrace();
		}finally {
			if(inputStream !=null) {
				try {
					inputStream.close();
				} catch (IOException e) {
					System.err.println("http get请求接口调用,异常信息:文件流关闭时异常，" +e.getMessage());
					e.printStackTrace();
				}
			}
		}
		
		return result;
	}
}
